package com.whccb.apps.office.document.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.HistoryTaskInstance;
import com.actionsoft.bpms.bpmn.engine.servicetask.ServiceDelegate;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.LogAPI;
import com.actionsoft.sdk.local.api.Logger;
import com.whccb.apps.office.document.util.CMSUtil;
import com.whccb.apps.office.document.util.DictUtil;

import net.sf.json.JSONArray;

public class CreateUrlCmsServiceAtGzzd extends ServiceDelegate {

	private static final Logger logger = LogAPI.getLogger(CreateUrlCmsServiceAtGzzd.class);
	
	public String getDescription() {
		return "规章制度/体系文件流程结束后，自动发布CMS内容，采用URL方式，套红的需要归档到发文模块下";
	}

	public String getProvider() {
		return "ActionSoft";
	}

	public String getVersion() {
		return "AWS 6.0";
	}

	public boolean execute(ProcessExecutionContext pec) throws Exception {
		logger.info("--------规章制度，进入发布CMS服务------------");
		
		Map<String, Object> paramMap = SDK.getProcessAPI().getVariables(pec.getProcessInstance().getId());
		
		if (paramMap != null && !paramMap.isEmpty()) {
			
			String boName = paramMap.get("BONAME") != null ? paramMap.get("BONAME").toString() : "";
			String zhmoduleid = paramMap.get("ZHCMSMODULEID") != null ? paramMap.get("ZHCMSMODULEID").toString() : "";
			String fhmoduleid = paramMap.get("FHCMSMODULEID") != null ? paramMap.get("FHCMSMODULEID").toString() : "";
			String gxhmoduleid = paramMap.get("GXHCMSMODULEID") != null ? paramMap.get("GXHCMSMODULEID").toString() : "";
			String formDefId = paramMap.get("CMSFORMDEFID") != null ? paramMap.get("CMSFORMDEFID").toString() : "";

			logger.info("规章制度，进入发布CMS服务,====boName="+ boName);
			
			BO bo = SDK.getBOAPI().getByProcess(boName, pec.getProcessInstance().getId());
			
			if (bo != null) {
				String moduleid = "";
				String userDeptid = bo.getString("REG_ORG_CODE");
				logger.info("规章制度，进入发布CMS服务,所属部门REG_ORG_CODE="+ userDeptid);
				// 发文流程需要判断是总行发文/分行发文/管辖行发文.然后写到不同的cms区域。
				// String at =
				// "@getDeptExtInfo(@getSuperDept(@getAwsDeptIdByOuterId("
				// + userDeptid + ")),ORGCATEGORY)";

				String at = "@getUnitTypeByDept(@getAwsDeptIdByOuterId(" + userDeptid + "))";

				String deptType = SDK.getRuleAPI().executeAtScript(at);
				logger.info("规章制度，进入发布CMS服务,所属部门类型:"+ deptType);
				
				if ("GXH".equals(deptType)) {
					moduleid = gxhmoduleid;
				} else if ("SUBBANK".equals(deptType)) {
					moduleid = fhmoduleid;
				} else {
					moduleid = zhmoduleid;
				}
				
				logger.info("规章制度，进入发布CMS服务,MODULEID-----CMS栏目ID:"+ moduleid);
				// if (ODConstant.ZH_FLAG.equals(deptType)) {// 总行
				// moduleid = zhmoduleid;
				// }
				// if (ODConstant.FH_FLAG.equals(deptType)) {// 分行
				// moduleid = fhmoduleid;
				// }
				// if (ODConstant.GXH_FLAG.equals(deptType)) {// 管辖行
				// moduleid = gxhmoduleid;
				// }

				String zwPdfUrl = bo.getString("PDFURL");
				logger.info("规章制度，进入发布CMS服务,zwPdfUrl="+zwPdfUrl);
				
				if (StringUtils.isNotBlank(zwPdfUrl)) {
					
					String title = "";
					String reg_level_dict = bo.getString("REG_LEVEL_DICT");
					// 01:纲要政策|02:基本管理制度|03:具体管理制度|04:体系文件|05:分行管辖行层级制度
					if (StringUtils.isNotBlank(reg_level_dict)) {
						String fileTypeName = DictUtil.getDictValue("WHBK.OD.GRC.FILE.TYPE", reg_level_dict);
						title = "<" + fileTypeName + ">";
					}

					if (StringUtils.isNotBlank(bo.getString("FILE_NAME"))) {
						title = title + bo.getString("FILE_NAME");
					}
					
					title = SDK.getRuleAPI().executeAtScript("@substring(" + title + ",0,100)");
					
					logger.info("规章制度，进入发布CMS服务,title="+title);

					if (StringUtils.isNotBlank(moduleid)) {
						String taskInstId = "";
						List<HistoryTaskInstance> hisTaskList = SDK.getHistoryTaskQueryAPI()
								.processInstId(pec.getProcessInstance().getId()).activityType("userTask")
								.orderByEndTime().desc().list();
						
						if (CollectionUtils.isNotEmpty(hisTaskList)) {
							taskInstId = hisTaskList.get(0).getId();
						}
						
						String createUserId = bo.getString("REG_USER_CODE");
						
						/**
						 * 添加附件
						 */
						JSONArray attachmentList = CMSUtil.getAttach(bo.getId(), "ZW", "ACCESSORY_ATTFILE");
						
						// 调用发布cms数据的方法
						String cmsid = CMSUtil.createUrlCmsData(pec.getUserContext(), moduleid,
								pec.getProcessInstance().getId(), taskInstId, formDefId, title, attachmentList, null, boName,
								"PDFFILE", "ACCESSORY_ATTFILE", createUserId);
						
						String updateSql = " UPDATE " + boName + " SET CMSMODELID =:CMSMODELID,REFCMSID=:REFCMSID WHERE ID = :ID";
						Map<String, Object> updateMap = new HashMap<>();
						updateMap.put("CMSMODELID", moduleid);
						updateMap.put("REFCMSID", cmsid);
						updateMap.put("ID", bo.getId());
						DBSql.update(updateSql, updateMap);
					}
				}
			}
		}
		logger.info("--------规章制度，发布CMS服务完成------------");
		return true;
	}

}
